package com.huacheng.authorization.service;

import com.huacheng.authorization.mapper.AuthorizationMapper;
import com.huacheng.authorization.pojo.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SpringDataUserDetailsService implements UserDetailsService {

    @Autowired
    private AuthorizationMapper securityMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDao user = securityMapper.findByUserName(username);
        if(user == null) {
            return null;
        }
        List<String> authorization = securityMapper.findByIdAuthorization(user.getId());
        String[] str = new String[authorization.size()];
        authorization.toArray(str);
        return User.withUsername(user.getUsername()).password(user.getPassword()).authorities(str).build();
    }
}
